// 云函数入口文件
const cloud = require('wx-server-sdk');
const rp = require('request-promise');
const crypt = require('./Crypt');

cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})

const decryptPhone = async (event) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const appid = wxContext.APPID
  const encryptedData = event.encryptedData
  const iv = event.iv
  const session_key = event.session_key
  console.log("调用云函数成功，参数如下：")
  console.log("iv的值： ",iv)
  console.log("openid: ",openid)
  console.log("appid: ",appid)
  console.log('session_key: ',session_key)
  let decodeResult = await crypt.decryptData(encryptedData, iv, appid, session_key)
  console.log('解密结果为：',decodeResult,"\n")
  return { data: decodeResult }
}
const getSessionKey = async (event)=>{
  const code = event.code
  if(code == '' || code == undefined){
    console.error("code不能为空.")
    return {data: undefined, errMsg: 'code不能为空.'}
  }
  //获取session_key接口
  const url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxf2c36153f9bb62b4&secret=7d4cb37d22cd887af57394ec73527f56&js_code=" + code + "&grant_type=authorization_code"
  return await rp(url).then(async resp => {
    console.log('获取session_key返回的结果为：',resp)
    resp = JSON.parse(resp)
    const session_key = resp.session_key
    console.log("获得session_key值为: ",session_key + "\n")
    return {session_key: session_key}
  }).catch(error=>{
    return null
  })
}
/**功能：
 * 一，获取用户session_key
 * 二，解密
 */
exports.main = async (event, context) => {
  console.log("云函数被调用，输入参数为：")
  console.log(event)
  const reqType = event.reqType
  switch(reqType){
    case 'getSessionKey':
      return await getSessionKey(event)
    case 'decryptMobile':
      return await decryptPhone(event)
    default:
      console.error('请求类型不存在.')
      return { data: undefined, errMsg: '请求类型不存在' }    
  }
}